﻿
function socketServer() {
  var { io } = require('../app');
  var Users = require('../service/user');
  var usersArr = [];
  var chatArr = [];

  io.on('connection', (socket) => {
    socket.on('disconnect', () => {
      var time = getTime();
      usersArr.map((item, index1) => {
        item.webPage.map((page, index2) => {
          // 匹配id, 正确删除
          if (page.id == socket.id) {
            item.webPage.splice(index2, 1);
            //console.log(time + ' ' + item.name + '关闭了' + page.title);
          }
          if (item.webPage.length <= 0) {
            //console.log(time + ' ' + item.name + '关闭了' + page.title);
            usersArr.splice(index1, 1);
            usersArr.map(arr => {
              arr.webPage.map(pages => {
                io.sockets.connected[pages.id].emit('receiveNotice', {des:item.name + '下线了',state:'info'});
              })
            });
            //console.log(time + ' ' + item.name + '下线了，还有' + usersArr.length + '人');
            onlineAjax(item._id, '离线');
          }
        });
      });
      chatArr.map((page,index)=>{
        if(page.pageId==socket.id){
          chatArr.splice(index,1);
        }
      })
    });

    socket.on('login', (data) => {
      var { name, _id, pageTitle } = data;
      var time = getTime();
      var matchUser = usersArr.filter(item => item.name == name);
      if (matchUser.length != 0) {
        matchUser[0].webPage.push({ id: socket.id, title: pageTitle });
        //console.log(time + ' ' + name + '打开了' + pageTitle);
      } else {
        data.webPage = [{ id: socket.id, title: pageTitle }];
        usersArr.map(item => {
          item.webPage.map(page => {
            io.sockets.connected[page.id].emit('receiveNotice', {des:name + '上线了',state:'success'});
          })
        });
        usersArr.unshift(data);
        //console.log(time + ' ' + name + '上线了，有' + usersArr.length + '人在线');
        //console.log(time + ' ' + name + '打开了' + pageTitle);
        var obj = { num: usersArr.length, online: '在线' }
        onlineAjax(_id, '在线');
        socket.emit('online', obj);
      }
    });

    socket.on('sendMessage', (data) => {
      thisname = data.fromUserName;
      toName = data.toUserName;
      message = data.message.replace(/[\r\n]/g, "");
      var toUser = usersArr.filter(item => item.name == toName);
      if(toName=='**********'){
        var thisPage = chatArr.filter(item=>item._id==data.fromUserId);
        if(thisPage.length==0) chatArr.push({_id:data.fromUserId,pageId:socket.id});
        chatArr.map(page=>{
          if(page._id==data.fromUserId){
            page.pageId=socket.id;
          }else{
            io.sockets.connected[page.pageId].emit('getchatGroup', {content:message,name:thisname,_id:data.fromUserId,time:getTime(),imgSrc:data.imgSrc,msgType:0});
          } 
        })
        socket.emit('getchatGroup', {content:message,name:thisname,_id:data.fromUserId,time:getTime(),imgSrc:data.imgSrc,msgType:0});
      }
      else if (toUser.length == 0) {
        socket.emit('receiveNotice', {des:toName + '不在线',state:'error'});
        return false;
      }else if(data.fromUserId==toUser[0]._id){
        return socket.emit('receiveNotice', {des:'你不能给自己发消息',state:'error'});
      } else {
        toUser[0].webPage.map(page => {
          setTimeout(() => {
            io.sockets.connected[page.id].emit('receiveNotice', {des:thisname + '给你发来了一个新的消息',state:'success',name:thisname});
          }, 500);
        })
        messageAjax({id:data.fromUserId},{id:toUser[0]._id},message);
        setTimeout(()=>{socket.emit('receiveNotice', {des:toName + '已收到消息',state:'success',name:toName})},500);
      }
    });


  });

  // 获取日期时间
  function getTime() {
    var date = new Date();
    var time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${addZero(date.getHours())}:${addZero(date.getMinutes())}:${addZero(date.getSeconds())}`;
    function addZero(num) {
      if (num < 10) return `0${num}`;
      else return num;
    }
    return time;
  }

  function onlineAjax(id, online) {
    var users = {};
    users.online = online;
    users = JSON.stringify(users);
    users = JSON.parse(users);
    Users.findByIdAndUpdate(id, users, function (err) {
      if (err) console.log(err);
    })
  }
}

 function messageAjax(fromUser,toUser,message) {
  var Users = require('../service/user');
  Users.findById(fromUser.id,function(err,users){
    if (err) console.log(err);
    else {
      users = JSON.stringify(users);
      users = JSON.parse(users);
      var date = new Date();
      var time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${addZero(date.getHours())}:${addZero(date.getMinutes())}:${addZero(date.getSeconds())}`;
      if(users.chatMessage.length==0){
        users.chatMessage=[{
          _id:toUser.id,
          history:[{
            content:message,
            msgType:1,time:time,read:0
          }]
        }]
      }else{
        if(users.chatMessage.filter(chat=>chat._id == toUser.id).length==0){
          users.chatMessage.push({
            _id:toUser.id,
            history:[{
              content:message,
              msgType:1,time:time,read:0
            }]
          })
        }else{
          users.chatMessage.map(chat=>{
            if(chat._id == toUser.id){
              chat.history.push({content:message,
                msgType:1,time:time,read:0})
            }
          })
        }
      }
      Users.findByIdAndUpdate(fromUser.id, users, function (err) {
        if (err) console.log(err);
      })
    }
  })
  Users.findById(toUser.id,function(err,users){
    if (err) console.log(err);
    else {
      users = JSON.stringify(users);
      users = JSON.parse(users);
      var date = new Date();
      var time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${addZero(date.getHours())}:${addZero(date.getMinutes())}:${addZero(date.getSeconds())}`;
      if(users.chatMessage.length==0){
        users.chatMessage=[{
          _id:fromUser.id,
          history:[{
            content:message,
            msgType:0,time:time,read:0
          }]
        }]
      }else{
        if(users.chatMessage.filter(chat=>chat._id == fromUser.id).length==0){
          users.chatMessage.push({
            _id:fromUser.id,
            history:[{
              content:message,
              msgType:0,time:time,read:0
            }]
          })
        }else{
          users.chatMessage.map(chat=>{
          if(chat._id == fromUser.id){
            chat.history.push({content:message,
              msgType:0,time:time,read:0})
          }
          })
        }
        
      }
      Users.findByIdAndUpdate(toUser.id, users, function (err) {
        if (err) console.log(err);
      })
    }
  })
}

// 补零
function addZero(num) {
  if (num < 10) return `0${num}`;
  else return num;
}


module.exports = socketServer;
